package admin

import (
	"go-ecommerce/internal/model"
	"go-ecommerce/internal/service"
	"go-ecommerce/internal/utils"
	"go-ecommerce/internal/validate"
	"gorm.io/gorm"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// CreateOrUpdateMenuHandler 创建或更新菜单
func CreateOrUpdateMenuHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req validate.CreateOrUpdateMenuRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			utils.Error(c, http.StatusBadRequest, "参数错误"+err.Error())
			return
		}

		menu := model.Menu{
			ID:           req.ID,
			ParentID:     req.ParentID,
			Title:        req.Title,
			Icon:         req.Icon,
			Path:         req.Path,
			PermissionID: req.PermissionID,
			Sort:         req.Sort,
			IsHidden:     req.IsHidden,
		}
		if err := service.CreateOrUpdateMenu(db, &menu); err != nil {
			utils.Error(c, http.StatusInternalServerError, "保存失败"+err.Error())
			return
		}
		utils.Success(c, "保存成功", menu)
	}
}

// GetMenuListHandler 获取菜单列表
func GetMenuListHandler(db *gorm.DB) gin.HandlerFunc {

	return func(c *gin.Context) {
		list, err := service.GetMenuList(db)
		if err != nil {
			utils.Error(c, http.StatusInternalServerError, "获取菜单失败")
			return
		}

		utils.Success(c, "获取成功", list)
	}
}

// DeleteMenuHandler 删除菜单
func DeleteMenuHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		idStr := c.Param("id")
		id, err := strconv.ParseUint(idStr, 10, 64)
		if err != nil || id <= 0 {
			utils.Error(c, http.StatusBadRequest, "ID错误")
			return
		}

		if err := service.DeleteMenu(db, id); err != nil {
			utils.Error(c, http.StatusInternalServerError, "删除失败")
			return
		}
		utils.Success(c, "删除成功", nil)
	}
}

// GetMenuTreeHandler 返回当前登录管理员可见的菜单树
func GetMenuTreeHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		adminIDStr, _ := c.Get("admin_id")
		adminID := adminIDStr.(uint)
		// 获取权限
		permissionIDs, err := service.GetAdminPermissionIDs(db, adminID)
		if err != nil {
			utils.Error(c, http.StatusInternalServerError, "获取权限失败"+err.Error())
			return
		}
		// 构建菜单树
		menuTree, err := service.BuildMenuTreeByPermissions(db, permissionIDs)
		if err != nil {
			utils.Error(c, http.StatusInternalServerError, "构建菜单失败"+err.Error())
			return
		}

		utils.Success(c, "获取成功", menuTree)
	}
}
